package com.extweb4j.web.controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import com.extweb4j.core.anno.AuthAnno;
import com.extweb4j.core.anno.Log;
import com.extweb4j.core.controller.ExtController;
import com.extweb4j.core.enums.RowStatus;
import com.extweb4j.core.kit.ExtKit;
import com.extweb4j.core.kit.LoginKit;
import com.extweb4j.core.kit.Pinyin4jKit;
import com.extweb4j.core.model.ExtUser;
import com.extweb4j.core.model.ExtUserRole;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
/**
 * 用户控制器
 * @author Administrator
 *
 */
public class UserController extends ExtController{
	/**
	 * 列表
	 */
	@AuthAnno
	public void list(){
		int page = getParaToInt("page");
		int limit = getParaToInt("limit");
		String keywords = getPara("keywords");
		Page<ExtUser> pageData = ExtUser.dao.pageUserBy(page,limit,keywords);
		
		for(ExtUser user : pageData.getList()){
			user.put("roles",ExtUserRole.dao.findRoleByUserId(user.getStr("id")));
		}
		renderJson(pageData);
	}
	/**
	 * 新增
	 */
	@Log("创建用户")
	@AuthAnno
	@Before(Tx.class)
	public void add(){
		ExtUser user = getExtModel(ExtUser.class);
		/**
		 * 验证用户是否存在
		 */
		if(ExtUser.dao.isExist(user.getStr("user_id"))){
			throw new RuntimeException("您输入的账号名已存在,请更换");
		}
		user.set("id",ExtKit.UUID());
		user.set("user_pwd",ExtKit.MD5(user.getStr("user_pwd")));
		user.set("row_status", RowStatus.启用.getState());
		user.set("create_time",new Timestamp(new Date().getTime()));
		user.set("pinyin", Pinyin4jKit.converterToSpell(user.getStr("user_name")));
		user.set("short_pinyin", Pinyin4jKit.converterToFirstSpell(user.getStr("user_name")));
		user.save();
		//绑定角色
		String[] roleIds = getParaValues("role_id");
		
		if(ArrayUtils.isEmpty(roleIds)){
			throw new RuntimeException("无效的角色");
		}
		for(String  roleId : roleIds){
			ExtUserRole eur = new ExtUserRole();
			eur.set("id", ExtKit.UUID());
			eur.set("user_id", user.getStr("id"));
			eur.set("role_id", roleId);
			eur.save();
		}
		success();
	}
	/**
	 * 编辑
	 */
	@Log("编辑用户")
	@AuthAnno
	@Before(Tx.class)
	public void edit(){
		ExtUser user = getExtModel(ExtUser.class);
		if(user.getStr("user_pwd") != null){
			user.set("user_pwd",ExtKit.MD5(user.getStr("user_pwd")));
		}
		user.set("pinyin", Pinyin4jKit.converterToSpell(user.getStr("user_name")));
		user.set("short_pinyin", Pinyin4jKit.converterToFirstSpell(user.getStr("user_name")));
		user.update();
		
		//绑定角色
		String[] roleIds = getParaValues("role_id");
		
		if(ArrayUtils.isEmpty(roleIds)){
			throw new RuntimeException("无效的角色");
		}
		ExtUserRole.dao.deleteByAttr("user_id", user.getStr("id"));
		for(String  roleId : roleIds){
			ExtUserRole eur = new ExtUserRole();
			eur.set("id", ExtKit.UUID());
			eur.set("user_id", user.getStr("id"));
			eur.set("role_id", roleId);
			eur.save();
		}
		
		success();
	}
	/**
	 * 逻辑删除
	 */
	@Log("删除用户")
	@AuthAnno
	@Before(Tx.class)
	public void delete(){
		ExtUser user = ExtUser.dao.findById(getPara("id"));
		if(user == null){
			throw new RuntimeException("要删除的用户不存在");
		}
		user.delete();
		success();
	}
	
	/**
	 * 根据Id获取一条记录，编辑
	 */
	public void get(){
		ExtUser user = ExtUser.dao.findById(getPara("id"));
		List<ExtUserRole> userRoles = ExtUserRole.dao.findByAttr("user_id",user.getStr("id"));
		List<String> roleIds = new ArrayList<String>();
		for(ExtUserRole ext : userRoles){
			roleIds.add(ext.getStr("role_id"));
		}
		user.put("role_id",roleIds);
		renderJson(new Record().set("success",true).set("data",user));
	}
	
	/**
	 * 获取当前登录用户信息
	 */
	public void getMe(){
		
		ExtUser user =  LoginKit.getSessionUser(getRequest());
		List<ExtUserRole> userRoles = ExtUserRole.dao.findByAttr("user_id",user.getStr("id"));
		List<String> roleIds = new ArrayList<String>();
		for(ExtUserRole ext : userRoles){
			roleIds.add(ext.getStr("role_id"));
		}
		user.put("role_id",roleIds);
		renderJson(new Record().set("success",true).set("data",user));
	}
	
	
	/**
	 * 重置密码
	 */
	@Log("重置用户密码")
	@AuthAnno
	public void resetpwd(){
		String id = getPara("id");
		String new_pwd = getPara("new_pwd");
		if(StringUtils.isBlank(id) || StringUtils.isBlank(new_pwd)){
			throw new RuntimeException("客户端参数不正确");
		}
		
		ExtUser user = ExtUser.dao.findById(id);
		if(user == null){
			throw new RuntimeException("用不存在或已删除");
		}
		user.set("user_pwd", ExtKit.MD5(new_pwd));
		user.update();
		success();
	}
	/**
	 * 用户修改密码
	 */
	@Log("修改密码")
	@AuthAnno
	public void updatepwd(){
		String user_pwd = getPara("user_pwd");
		String new_pwd1 = getPara("new_pwd1");
		String new_pwd2 = getPara("new_pwd2");
		
		ExtUser user = LoginKit.getSessionUser(getRequest());
		
		if(!ExtKit.MD5(user_pwd).equals(user.getStr("user_pwd"))){
			throw new RuntimeException("旧密码输入错误");
		}
		
		if(!new_pwd1.equals(new_pwd2)){
			throw new RuntimeException("两次输入的密码不一致");
		}
		
		user.set("user_pwd", ExtKit.MD5(new_pwd1));
		user.update();
		success("密码修改成功");
	}
	
	public static void main(String[] args) {
		System.out.println(ExtKit.MD5("123456"));
	}
}
